package com.dosgi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dosgi.kit.ThreadPoolKit;

/**
 * 容器类，放在context工程中，模块里面会用到，不放在agent里面，否则模块还得依赖agent
 * 
 * @author dingnate
 *
 */
public class Dosgi {
	private static transient final Logger LOG = LoggerFactory.getLogger(Dosgi.class);
	public static final String MODULE_HOME_KEY = "module.home";
	public static final String PHASE_SYSTEM = "System";
	private static DosgiLifeCycle lifeCycle = new DosgiLifeCycle();

	/**
	 * 容器包含唯一上下文
	 */
	private static DosgiContextDefault CTX;

	public static IDosgiContext context() {
		return CTX;
	}

	/**
	 * @param clazz
	 * @param bean
	 */
	public static void registry(Class<?> clazz, Object bean) {
		CTX.beanFactory().registry(clazz, bean);
	}

	/**
	 * 从上下文取注册服务
	 * 
	 * @param clazz
	 * @return
	 */
	public static <T> T get(Class<T> clazz) {
		return CTX.beanFactory().get(clazz);
	}

	/**
	 * 独立应用（standalone application），在非启动线程调用关闭dosgi
	 */
	public static void close() {
		CTX.stop();
		ThreadPoolKit.stop();
		lifeCycle.setState(LifeCycleState.CLOSED);
		LOG.info("dosgi close success.");
	}

	/**
	 * @return the lifeCycle
	 */
	public static final DosgiLifeCycle getLifeCycle() {
		return lifeCycle;
	}

	/**
	 * 启动dosgi独立应用
	 * @param moduleHome 模块主目录
	 */
	public static final void start(String moduleHome) {
		start(moduleHome, true);
	}

	/**
	 * 启动dosgi
	 * @param moduleHome 模块主目录
	 * @param standalone 独立应用true,在非当前线程中调用Dosgi.close()关闭<br>
	 * 					   嵌入式非独立应用false
	 */
	public static final void start(String moduleHome, boolean standalone) {
		CTX = new DosgiContextDefault(moduleHome);
		CTX.start(standalone);
	}

	/**
	 * @return 模块主目录
	 */
	public static final String getModuleHome() {
		return CTX.getModuleHome();
	}
}
